package service

import (
	"encoding/json"
	"gin/common"
	"gin/model"
	"gin/queue"
	"gin/tai/dict/word"
	"gin/validate"
	"github.com/spf13/viper"
	nlp "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/nlp/v20190408"
	"time"
)

func CreateSentenceWord(Data validate.AddSentenceWord) (sentenceWordModel model.SentenceWord, err error) {
	sentenceWordModel.Word = Data.Word
	sentenceWordModel.BeginOffset = Data.BeginOffset
	sentenceWordModel.Length = Data.Length
	sentenceWordModel.Pos = Data.Pos
	sentenceWordModel.SentenceId = Data.SentenceId

	_, err = sentenceWordModel.Insert()
	return
}

func FindSentenceWord(Param common.SelectQueryParam) (resData model.SentenceWord, err error) {
	var logModel model.SentenceWord

	resData, err = logModel.Find(Param)

	return
}

func SelectSentenceWord(Param common.SelectQueryParam) (total int64, resData []model.SentenceWord, err error) {
	var logModel model.SentenceWord

	total, resData, err = logModel.Select(Param)

	return
}

func UpdateSentenceWord(Data validate.UpdateSentenceWord) (resData model.SentenceWord, err error) {

	resData, err = resData.Update(model.SentenceWord{
		Id:          Data.Id,
		BeginOffset: Data.BeginOffset,
		Word:        Data.Word,
		Length:      Data.Length,
		Pos:         Data.Pos,
		SentenceId:  Data.SentenceId,
	})
	return
}

// 删除段落词语
func DeleteSentenceWord(param *common.Filter) {

	var logModel model.SentenceWord
	logModel.DeleteByFilter(param)
	return
}

// 查询相似词
func QuerySimilarWords(Param common.SelectQueryParam, number uint64, isAsync bool) (map[uint64][]*string, error) {
	var SentenceWord model.SentenceWord
	var wordsMap = make(map[uint64][]*string)

	total, logModels, err := SentenceWord.Select(Param)
	if err != nil || total <= 0 {
		return wordsMap, err
	}

	if number == 0 {
		number = 20
	}
	var response *nlp.SimilarWordsResponse

	for index, sentenceWord := range logModels {

		if isAsync {

			queue.EnQueue(&queue.QuerySimilarWordsJob{
				SentenceWordId: sentenceWord.Id,
				Number:         number,
			})
			continue
		}

		if index != 0 && index%viper.GetInt("tai.maxQuerySec") == 0 {
			time.Sleep(time.Duration(1) * time.Second)
		}

		if sentenceWord.Word == "" {
			continue
		}

		response, err = word.Similar(sentenceWord.Word, number)

		if err != nil {
			continue
		}
		wordsMap[sentenceWord.Id] = response.Response.SimilarWords

		similarLength := len(wordsMap[sentenceWord.Id])
		if similarLength <= 0 {
			continue
		}

		var wordModel model.Word
		existRecord, err := wordModel.Find(common.SelectQueryParam{
			Fields: "*",
			Limit:  1,
			Offset: 0,
			Order:  "id desc",
			Filter: common.Filter{Filter: map[string]interface{}{
				"-eq": map[string]interface{}{
					"condition": "word = ?",
					"val":       sentenceWord.Word,
				},
			},
			},
		})

		// 没有保存过该词语的就写入
		if err != nil || existRecord.Id <= 0 {
			wordModel.Word = sentenceWord.Word
			id, err := wordModel.Insert()
			if err != nil {
				continue
			}
			var similarModel model.WordSimilar
			similarWordModels := make([]model.WordSimilar, similarLength)
			for index, similarWord := range response.Response.SimilarWords {
				similarWordModels[index].Word = *similarWord
				similarWordModels[index].WordId = id
				similarWordModels[index].SourceWord = sentenceWord.Word
			}
			similarModel.InsertAll(&similarWordModels)
		}

		var SimilarWordsByte []byte

		SimilarWordsByte, err = json.Marshal(&response.Response.SimilarWords)
		if err != nil {
			continue
		}
		_, err = sentenceWord.Update(model.SentenceWord{
			Id:           sentenceWord.Id,
			SimilarWords: SimilarWordsByte,
		})
		if err != nil {
			continue
		}

	}

	return wordsMap, err
}
